<template>
  <div
    :class="[
      'develop-view-basic',
      handleType == 'view' || handleType == 'development-audit' ? 'develop-view' : '',
    ]"
  >
    <el-form
      ref="formRef"
      :rules="rules"
      :model="form"
      label-width="100"
      size="default"
      :label-position="
        handleType == 'view' || handleType == 'development-audit' ? 'right' : 'top'
      "
    >
      <el-row :gutter="20">
        <el-col :span="20" v-if="type == 'default'">
          <el-form-item label="采购链接：" prop="gathering_link">
            <div
              class="w-full"
              v-if="handleType == 'view' || handleType == 'development-audit'"
            >
              <template v-if="is_gathering_link">
                <vText :value="form.gathering_link" :copy="true"></vText>
              </template>
              <template v-else>--</template>
            </div>
            <template v-else>
              <el-input
                v-model="form.gathering_link"
                placeholder="请输入"
                class="input-with-select"
              >
                <template #append>
                  <el-button
                    class="gather"
                    type="primary"
                    :loading="loading"
                    @click="handleGather"
                    >采集</el-button
                  >
                </template>
              </el-input>
            </template>
          </el-form-item>
        </el-col>

        <div class="ml-5 basic-img">
          <template v-if="handleType === 'view' || handleType == 'development-audit'">
            <VImage :src="form.product_main_img_watermark || form.product_main_img">
            </VImage>
          </template>
          <template v-else>
            <UploadImg
              v-model:imageUrl="form.product_main_img"
              width="100px"
              height="100px"
              :file-size="2"
            >
              <template #empty>
                <svg-icon class="base-text-color" icon-class="Plus"></svg-icon>
                <span class="base-text-color">上传图片</span>
              </template>
            </UploadImg>
          </template>
        </div>
      </el-row>

      <el-row :gutter="20">
        <el-col
          :span="handleType == 'view' || handleType == 'development-audit' ? 21 : 8"
        >
          <el-form-item
            label="产品分类："
            :prop="
              handleType != 'view' && handleType != 'development-audit'
                ? 'product_category'
                : ''
            "
          >
            <template v-if="handleType == 'view' || handleType == 'development-audit'">
              {{ form.product_category_text }}
            </template>
            <template v-else>
              <select-category
                v-model="form.product_category"
                filterable
                class="w-full"
                :defaultProps="defaultProps"
                :showAllLevels="true"
                @change="changeCategory"
              ></select-category>
            </template>
          </el-form-item>
        </el-col>
        <el-col
          :span="handleType == 'view' || handleType == 'development-audit' ? 21 : 8"
        >
          <el-form-item
            label="产品名称："
            :prop="
              handleType != 'view' && handleType != 'development-audit'
                ? 'product_title'
                : ''
            "
          >
            <template v-if="handleType == 'view' || handleType == 'development-audit'">
              {{ form.product_title }}
            </template>
            <template v-else>
              <el-input
                v-model.trim="form.product_title"
                placeholder="请输入"
                clearable
              />
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="type == 'default'">
          <el-form-item class="relative" label="运营是否参与审核：" label-width="140">
            <template #label
              >运营是否参与审核:
              <el-tooltip placement="top">
                <template #content>
                  说明<br />1.若无需运营参与审核，则此按钮改为否即可；<br />2、若需要运营参与审核，则开启此功能后，推荐平台、站点必须维护运营人员
                </template>
                <svg-icon
                  class="absolute left-[128px] top-1"
                  icon-class="QuestionFilled"
                ></svg-icon>
              </el-tooltip>
            </template>
            <span
              class="ml-2"
              v-if="handleType == 'view' || handleType == 'development-audit'"
            >
              {{ form.is_operation_check == 1 ? "是" : "否" }}
            </span>
            <template v-else>
              <el-switch
                v-model="form.is_operation_check"
                :active-value="1"
                :inactive-value="0"
              />
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="type == 'default'">
          <el-form-item
            label="产品开发："
            :prop="
              handleType != 'view' && handleType != 'development-audit'
                ? 'developer_id'
                : ''
            "
          >
            <template v-if="handleType == 'view' || handleType == 'development-audit'">
              {{ form.developer_text }}
            </template>
            <template v-else>
              <select-personnel
                class="w-full"
                v-model="form.developer_id"
                placeholder="请选择产品开发"
              />
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="type == 'default'">
          <el-form-item label="开发审核人员：" label-width="120">
            <template v-if="handleType == 'view' || handleType == 'development-audit'">
              {{ form.reviewer_text }}
            </template>
            <template v-else>
              <select-personnel
                class="w-full"
                v-model="form.reviewer_id"
                placeholder="请选择开发审核人员"
              ></select-personnel>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="起批量：">
            <template v-if="handleType == 'view' || handleType == 'development-audit'">
              {{ form.min_order }}
            </template>
            <template v-else>
              <el-input
                placeholder="请输入"
                v-model="form.min_order"
                @input="form.min_order = form.min_order.replace(/^(0+)|[^\d]+/g, '')"
              />
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购天数：">
            <template v-if="handleType == 'view' || handleType == 'development-audit'">
              {{ form.purchase_days }} 天
            </template>
            <template v-else>
              <el-input
                placeholder="请输入"
                v-model="form.purchase_days"
                @input="
                  form.purchase_days = form.purchase_days.replace(/^(0+)|[^\d]+/g, '')
                "
              />
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="装箱数量：">
            <template v-if="handleType == 'view' || handleType == 'development-audit'">
              {{ form.packing_quantity }}
            </template>
            <template v-else>
              <el-input
                placeholder="请输入"
                v-model="form.packing_quantity"
                @input="
                  form.packing_quantity = form.packing_quantity.replace(
                    /^(0+)|[^\d]+/g,
                    ''
                  )
                "
              />
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物流属性：">
            <template v-if="handleType == 'view' || handleType == 'development-audit'">
              {{ form.logistic_attr_text }}
            </template>
            <template v-else>
              <select-logistics
                class="w-full"
                v-model="form.logistic_attr"
                placeholder="请选择"
                @change="changeLogistics"
              ></select-logistics>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="handleType == 'view' || handleType == 'development-audit' ? 8 : 6">
          <el-form-item label="产品属性：">
            <template v-if="handleType == 'view' || handleType == 'development-audit'">
              {{ form.attribute_type_text }}
            </template>
            <template v-else>
              <el-radio-group v-model="form.attribute_type" @change="changeAttribute">
                <el-radio
                  v-for="dict in sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </template>
          </el-form-item>
        </el-col>
        <template v-if="form.attribute_type == 2">
          <el-col v-if="handleType == 'development-audit'" :span="8">
            <template v-for="item in form.specification" :key="item.label">
              <el-form-item :label="`${item.label}:`" label-position="left">
                <el-checkbox-group v-model="item.value">
                  <el-checkbox v-for="o in item.valueOptions" :label="o" :key="o">{{
                    o
                  }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </template>
          </el-col>
          <el-col
            v-else
            :span="handleType == 'view' ? 8 : handleType == 'development-audit' ? 8 : 6"
            v-for="(item, index) in form.specification"
            :key="index"
          >
            <el-form-item :label="`${item.label}：`">
              <template v-if="handleType == 'view'">
                {{ item.value && item.value.join("、") }}
              </template>
              <template v-else>
                <el-select
                  class="w-full"
                  v-model="item.value"
                  multiple
                  clearable
                  collapse-tags
                  collapse-tags-tooltip
                  filterable
                  allow-create
                  default-first-option
                  :reserve-keyword="false"
                  placeholder="请选择"
                >
                  <el-option v-for="o in item.options" :key="o" :label="o" :value="o" />
                </el-select>
              </template>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
      <el-form-item
        label-position="top"
        label="审核备注"
        v-if="handleType == 'development-audit'"
      >
        <el-input
          v-model="form.review_remark"
          placeholder="请输入"
          :autosize="{ minRows: 4, maxRows: 10 }"
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <Attribute ref="AttributeRef" @selectAttribute="selectAttribute"></Attribute>
  </div>
</template>
<script setup name="Basic">
import api from "../../api";
import UploadImg from "@/components/UploadImg/index.vue";
import {
  reactive,
  toRefs,
  getCurrentInstance,
  nextTick,
  inject,
  watch,
  computed,
} from "vue";
import { ElMessage } from "element-plus";
import Attribute from "../Attribute.vue";
import SelectCategory from "@/components/SelectCategory/index.vue";
import { classified_auto_parts } from "@/utils/product/data.js";
import SelectLogistics from "@/components/SelectLogistics/index.vue";
import { fieldPermissionBoolen } from "@/utils/permission.js";
import VImage from "@/components/Image/index.vue";

const { proxy } = getCurrentInstance();
const emits = defineEmits(["update:value"]);
const props = defineProps({
  value: { type: Object, default: () => ({}) },
  handleType: { type: String, default: "view" },
  type: { type: String, default: "default" }, // 默认：查看 添加 修改 开发审核  其他：运营审核
});

const { handleType, type } = toRefs(props);

const defaultProps = {
  children: "son",
  label: "name",
  value: "id",
  checkStrictly: false,
};

const is_gathering_link = computed({
  get() {
    return fieldPermissionBoolen("gathering_link");
  },
  set(val) {},
});

const isLink = (url) => {
  const Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
  const objExp = new RegExp(Expression);
  return objExp.test(url);
};

const data = reactive({
  options: inject("options"),
  defaultOptions: [],
  loading: false,
  formRef: null,
  AttributeRef: null,
  ProfitTrialRef: null,
  sys_normal_disable: [
    { label: "单属性", value: 1 },
    { label: "多属性", value: 2 },
  ],
  rules: {
    product_title: [{ trigger: "blur", required: true, message: "请输入产品名称" }],
    product_category: [
      { required: true, message: "请选择商品分类", trigger: ["blur", "change"] },
    ],
    developer_id: [
      { required: true, message: "请选择产品开发", trigger: ["blur", "change"] },
    ],
    gathering_link: [
      {
        trigger: ["blur", "change"],
        validator: (rule, value, callback) => {
          if (value && !isLink(value)) {
            callback(new Error("链接不合法!"));
          } else {
            callback();
          }
        },
      },
    ],
  },
});

const { rules, loading, formRef, sys_normal_disable, AttributeRef, options } = toRefs(
  data
);

const form = computed(() => {
  return props.value;
});

const openAttribute = (data) => {
  nextTick(() => {
    AttributeRef.value.open(data);
  });
};
const validate = (callback) => {
  proxy.$refs["formRef"].validate((valid) => {
    callback(valid);
  });
};
// 处理采集数据
function toKeyValue(specification) {
  let attribute = [];
  const chkeys = Object.keys(specification);
  chkeys.forEach((key) => {
    let obj = {};
    obj["label"] = key;
    obj["options"] = specification[key];
    obj["checked"] = false;
    obj["value"] = null;
    attribute.push(obj);
  });
  return attribute;
}
// 采集数据
const handleGather = () => {
  if (!form.value.gathering_link) return ElMessage.error("请输入采购链接！");
  loading.value = true;
  api
    .gathering({ link: form.value.gathering_link })
    .then((res) => {
      let { specification, subject, image } = res.data;
      form.value.product_title = subject;
      form.value.product_main_img = image;
      const handleAttribute = toKeyValue(specification);
      if (handleAttribute.length > 2) {
        openAttribute(handleAttribute);
      } else {
        form.value.specification = toKeyValue(specification);
      }
    })
    .finally(() => {
      loading.value = false;
    });
};
// 选择多属性
const selectAttribute = (list) => {
  form.value.specification = list;
};

const changeAttribute = () => {
  if (form.value.specification.length == 0) return;
  form.value.specification.forEach((i) => {
    i.value = null;
  });
};

const reset = () => {
  proxy.resetForm("formRef");
};

const changeCategory = (val) => {
  if (handleType.value == "add" && val.length && classified_auto_parts.includes(val[0])) {
    form.value.is_operation_check = 1;
  }
};

const changeLogistics = (val) => {
  form.value.logistic_attr_text = val;
};

defineExpose({ open, validate, reset });
</script>
<style lang="scss">
.gather {
  background: #eaf3ff !important;
  color: #3487ff !important;
  border: 1px solid var(--base-border-color) !important;
}

.basic-img {
  width: 100px;
  height: 100px;
  position: absolute;
  right: 4px;
  z-index: 99;
}

.develop-view {
  .el-form-item {
    margin-bottom: 2px !important;
  }
}
</style>
